//
//  WCNRiskAccessmentRecordsVC.m
//  WCN
//
//  Created by 陈武琦 on 16/3/7.
//  Copyright © 2016年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNRiskAccessmentRecordsVC.h"
#import "WCNRiskAccessmentRecordsCell.h"
#import "WCNRiskAccessmentRecordsModel.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "WCNWebViewController.h"
#import "MJRefresh.h"
#import "WSJPickView.h"
#import "WCQestionnaireModel.h"
#import "UMMobClick/MobClick.h"
#import "Constants.h"

static NSString *cellID = @"riskAccessmentRecordsID";


@interface WCNRiskAccessmentRecordsVC ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSArray *models;
@property(nonatomic, copy)NSArray *dataArray;
@property (weak, nonatomic) MBProgressHUD *hud;
@property (nonatomic, strong) UIButton *footerBtn;
//风险评估的种类
@property (strong, nonatomic) NSArray *riskAccessArray;
//风险评估的标题
@property (strong, nonatomic) NSArray *riskAccessTitles;

//风险评估的左侧图标
@property (strong, nonatomic) NSArray *riskAccessIcons;

@end

@implementation WCNRiskAccessmentRecordsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kAppBg;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.tableView registerClass:[WCNRiskAccessmentRecordsCell class] forCellReuseIdentifier:cellID];
    defineWeakSelf;
    // 添加下拉刷新头部控件
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        //请求加载数据
        [weakSelf getDataFromWeb];
    } dateKey:@"WCNRiskAccessmentRecordsVCTableView"];
   
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf.tableView.footer endRefreshing];
        [weakSelf.tableView.footer noticeNoMoreData];
    }];
    [self.view addSubview:self.footerBtn];
    // Do any additional setup after loading the view.
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 - 40) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = kAppBg;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_tableView];
    }
    return  _tableView;
}

- (UIButton *)footerBtn{
    if (!_footerBtn) {
        _footerBtn =[UIButton buttonWithType:UIButtonTypeSystem];
        _footerBtn.frame =CGRectMake(30, kScreenHeight -35-65 - 40, kScreenWidth -60, 35);
        [_footerBtn setTitle:@"添加风险评估" forState:UIControlStateNormal];
        [_footerBtn setBackgroundColor:HexRGB_WSJ(84, 130, 255)];
        _footerBtn.layer.cornerRadius = 5;
        _footerBtn.layer.masksToBounds= YES;
        [_footerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_footerBtn addTarget:self action:@selector(addRecord) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _footerBtn;
    
}

- (void)addRecord {
    
        defineWeakSelf;
        WSJPickView *pickView = [WSJPickView pickView];
        pickView.pickTitle = @"风险评估";
        pickView.dataArray = self.riskAccessTitles;
        [pickView show];
        pickView.saveBlock = ^(NSString *selecStr, NSInteger index){
            
            //统计增加风险评估的事件
            [MobClick endEvent:AddEvaluateRecord];
            WCQestionnaireModel *model =self.riskAccessArray[index];
            WCNWebViewController *vc =[WCNWebViewController new];
            
            //拼接参数
            //    opFlag=0，
            //    qriId=4，
            //    questionId=4
            int recordId =  [weakSelf.recordId integerValue];
            int recordFlag = 2;
            int opFlag = 1;
            int nurseId = [[WCDefaultManager shareMg] nurseId];
            int questionId =[model.questionId integerValue];
            NSString *nurStr =[NSString stringWithFormat:@"%@?opFlag=%i&questionId=%i&nurseId=%i&recordId=%i&recordFlag=%i",model.httpUrl,opFlag,questionId,nurseId,recordId,recordFlag];
            NSString * urlStrCode = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)nurStr,NULL,NULL,kCFStringEncodingUTF8));
            vc.url =[NSURL URLWithString:urlStrCode];
            vc.title = @"风险评估";
            [self.blockNav () pushViewController:vc animated:YES];
        };
    
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear: animated];
    [self getDataFromWeb];

}

#pragma mark - 从服务器请求数据
- (void)getDataFromWeb{
    
    weakSelf_define;
    MBProgressHUD *hud;
    __block NSInteger count = 2;
    //获取问卷记录列表
    if (!self.hud) {
        hud = [[WCPopupLayerManager shareMg] showSimple:[UIApplication sharedApplication].keyWindow];
        self.hud = hud;
    }
 
    NSInteger nurseId =[[WCDefaultManager shareMg] nurseId];
    NSNumber *nurseNum = [NSNumber numberWithInteger:nurseId];
    NSDictionary *param = @{@"nurseId":nurseNum, @"recordId":self.recordId, @"qflag":@2};
    [[WCNetworkAccessManager sharedMg] GET:kRiskQuestionnaireRecords parameters:param success:^(NSDictionary *result){
        
        NSArray *data = result[@"data"];
        NSMutableArray *muarr = [NSMutableArray array];
            [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (!*stop) {
                    WCNRiskAccessmentRecordsModel *model = [[WCNRiskAccessmentRecordsModel alloc] init];
                    [model setValuesForKeysWithDictionary:obj];
                    [muarr addObject:model];
                }
            }];
        _models = [muarr copy];
        [weakSelf.tableView reloadData];
    } failure:nil netError:nil always:^{
        count--;
        if (count == 0) {
            
            [weakSelf.hud hide:YES];
        }
        [self.tableView.header endRefreshing];
    }];
    
    
    //获取问卷评估表的种类
    NSDictionary *params = @{@"nurseId":nurseNum, @"qbelong":@1, @"qflag":@2};
    [[WCNetworkAccessManager sharedMg] POST:KRiskQuestionnaire parameters:params success:^(NSDictionary *result){
        NSArray *data = result[@"data"];
        NSLog(@"%@",data);
        NSMutableArray *muarr = [NSMutableArray array];
        [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (!*stop) {
                WCQestionnaireModel *model = [[WCQestionnaireModel alloc] init];
                [model setValuesForKeysWithDictionary:obj];
                [muarr addObject:model];
            }
        }];
        
        self.riskAccessArray = [muarr copy];
        
    } failure:nil netError:nil always:^{
        count--;
        if (count == 0) {
             
            [self.hud hide:YES];
        }
    }];
    
}


- (void)setRiskAccessArray:(NSArray *)riskAccessArray {
    
    if (![_riskAccessArray isEqual:riskAccessArray]) {
        _riskAccessArray = [riskAccessArray copy];
        NSMutableArray *titlesArr = [NSMutableArray array];
        NSMutableArray *imagesArr = [NSMutableArray array];
        [riskAccessArray enumerateObjectsUsingBlock:^(WCQestionnaireModel  *model, NSUInteger idx, BOOL * _Nonnull stop) {
            if (!*stop) {
                [titlesArr addObject:model.name];
                [imagesArr addObject:@"CaseCell_BlueHeader"];
            }
        }];
        _riskAccessTitles = [titlesArr copy];
        _riskAccessIcons = [imagesArr copy];
    }
}

#pragma mark - <UITableViewData and UITableDelegate>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return [self.models count];

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([self.models count] > 0) {
        
        return [self cellHeightWith:self.models[indexPath.row]];
    }else {
    
        return 150;
    
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    WCNRiskAccessmentRecordsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    WCNRiskAccessmentRecordsModel *model = self.models[indexPath.row];
    
    cell.model = model;
    
        return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    WCNRiskAccessmentRecordsModel *model =self.models[indexPath.row];
    WCNWebViewController *vc =[WCNWebViewController new];
    
    int opFlag =[model.isOver integerValue]==0?1:0;
    NSInteger qriId =[model.qriId integerValue];
    NSInteger questionId =[model.questionId integerValue];
    NSString *nurStr =[NSString stringWithFormat:@"%@?opFlag=%i&qriId=%i&questionId=%i",model.qHttpUrl,opFlag,qriId,questionId];
    NSString * urlStrCode = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)nurStr,NULL,NULL,kCFStringEncodingUTF8));
    vc.url =[NSURL URLWithString:urlStrCode];
    vc.title = @"问卷详情";
    [self.blockNav () pushViewController:vc animated:YES];
}


- (CGFloat)cellHeightWith:(WCNRiskAccessmentRecordsModel *)model {

    CGFloat h1=[[model.column1Name stringByAppendingString:model.column1Description] boundingRectWithSize:CGSizeMake(kScreenWidth - 35, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size.height;
    CGFloat h2=[[model.column2Name stringByAppendingString:model.column2Description] boundingRectWithSize:CGSizeMake(kScreenWidth - 35, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size.height;
    CGFloat height = h1+h2+80;
    return  height;  //内容距离底部下划线10的距离

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {


    NSLog(@"---------------riskAccessmentRecordVC----------------");

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
